package com.ys.mq;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ys.constant.ShopCode;
import com.ys.entity.MQEntity;
import com.ys.mapper.UserMapper;
import com.ys.mapper.UserMoneyLogMapper;
import com.ys.pojo.TradeUser;
import com.ys.pojo.TradeUserMoneyLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}",
        consumerGroup = "${mq.order.consumer.group.name}",
        messageModel = MessageModel.BROADCASTING)
public class UserRockerMQListener implements RocketMQListener<MessageExt> {

    @Autowired
    private UserMoneyLogMapper userMoneyLogMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void onMessage(MessageExt messageExt) {
        //解析消息
        try {
            String body = new String(messageExt.getBody(), "UTF-8");

            MQEntity mqEntity = JSON.parseObject(body, MQEntity.class);

            log.info("收到消息");

            if (mqEntity.getUserMoney()!=null && mqEntity.getUserMoney().compareTo(BigDecimal.ZERO)>0){
                //修改余额
                TradeUser tradeUser = userMapper.selectById(mqEntity.getUserId());
                UpdateWrapper<TradeUser> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().set(TradeUser::getUserMoney,tradeUser.getUserMoney().add(mqEntity.getUserMoney()));
                userMapper.update(tradeUser,updateWrapper);
                log.info("余额退回成功");
                //生成退款日志记录

                TradeUserMoneyLog moneyLog = new TradeUserMoneyLog();
                moneyLog.setMoneyLogType(ShopCode.SHOP_USER_MONEY_REFUND.getCode());
                moneyLog.setCreateTime(new Date());
                moneyLog.setUseMoney(mqEntity.getUserMoney());
                moneyLog.setUserId(mqEntity.getUserId());
                moneyLog.setOrderId(mqEntity.getOrderId());
                userMoneyLogMapper.insert(moneyLog);
                log.info("生成退款订单日志");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
